odoo.define('lift_base.salvager_unit_map', function (require) {
    "use strict";
    var WebClient = require('web.AbstractWebClient');
    var ajax = require('web.ajax');
    var core = require('web.core');
    var Widget = require('web.Widget');
    var Model = require('web.Model');
    var session = require('web.session');
    var framework = require('web.framework');
    var common_widget = require('lift_base.common_widget');

   var SalvagerUnitMap = Widget.extend({
       template: "baidu_map_salvager_unit",
       init: function (parent) {
           this._super(parent);
           this.unit_markers = [];
           this.is_salvager_unit = false;
           this.current_area_id = -2;
           this.area_ids = [];
       },
       start: function () {
            var self = this;
           // 先查询默认城市
           common_widget.get_default_city(function (city) {
                self.city = city;
                self.init_load();
           });
       },
       init_load: function () {
           this.init_baidu_map();
           this.add_area_boundary();
           this.add_salvager_unit_markers();

           var btn_block = new SalvagerUnitMapBtnBlock(this);
           btn_block.on("show_or_hide_menu", this, this.show_or_hide_menu);
           btn_block.on("show_level_one", this, this.show_level_one);
           btn_block.on("show_level_two", this, this.show_level_two);
           btn_block.appendTo(this.$el);

           var area_list_widget = new SalvagerUnitMapAreaListWidget(this);
           area_list_widget.on("search_unit_by_area_id", this, this.search_unit_by_area_id);
           area_list_widget.on("get_area_company_count", this, this.get_area_company_count);
           area_list_widget.on("get_area_salvager_count", this, this.get_area_salvager_count);
           area_list_widget.appendTo(this.$el);

           var salvager_unit_search_widget = new SalvagerUnitSearchWidget(this, this.unit_markers);
           salvager_unit_search_widget.on("search_unit_by_id", this, this.search_unit_by_id);
           salvager_unit_search_widget.appendTo(btn_block.$el);

           this.init_show_or_hide_menu_text();
       },
       init_baidu_map: function () {
           var map = new BMap.Map(this.$el[0], {
                // minZoom : 10,
            });
            map.centerAndZoom(this.city.name, 10);
            map.enableScrollWheelZoom(true);
            // map.addControl(new BMap.MapTypeControl());
            this.map = map;
       },
       init_show_or_hide_menu_text: function () {
            var self = this;
            if($(".o_sub_menu").css("display") == "none" && $("#oe_main_menu_navbar").css("display") == "none"){
                self.$(".show_or_hide_menu").html("显示菜单");
            }else {
                self.$(".show_or_hide_menu").html("隐藏菜单");
            }
        },
        show_or_hide_menu: function () {
            $(".o_sub_menu").toggle();
            $("#oe_main_menu_navbar").toggle();
            this.init_show_or_hide_menu_text();
        },
       get_areas: function () {
            //获取下所有区
            var area_model = new Model("tyibs.base.province.city.area");
            return area_model.query(['name', 'ln', 'la', 'color']).filter([['city_id', '=', this.city.id]]).all();
        },
       add_area_boundary: function () {
            //添加各区/县边界线
            var self = this;
            self.get_areas().then(function (results) {
                results.forEach(function (item) {
                    self.area_ids.push(item.id);
                    if (item.name != "开发区"){
                        self.add_single_map_polygon(self.city.name + item.name, item.id, "", "", 3 , "");
                    }
                });
            });
        },
       add_single_map_polygon: function (name, id, fillColor, strokeColor, strokeWeight, angle_of_view) {
            /*
            生成单个的行政图层
            angle_of_view: 视角，city or area
             */
            var self = this;
            var bdary = new BMap.Boundary();
            // var instead_name = name == "开发区" ? "驿城区" : name;
            bdary.get(name, function(rs) {       //获取行政区域
                var count = rs.boundaries.length; //行政区域的点有多少个
                if (count === 0) {
                    return;
                }
                fillColor = fillColor != undefined ? fillColor : '';
                strokeColor = strokeColor != undefined && strokeColor != "" ? strokeColor : 'red';
                strokeWeight = strokeWeight != undefined ? strokeWeight : 1;
                for (var i = 0; i < count; i++) {
                    var ply = new BMap.Polygon(rs.boundaries[i], {
                        strokeWeight: strokeWeight, strokeColor: strokeColor,
                        fillColor: fillColor, fillOpacity: 0.8, strokeStyle: 'dashed'
                    }); //建立多边形覆盖物

                    self.map.addOverlay(ply);
                }
            })
        },
       add_salvager_unit_markers: function () {
           var self = this;
           var query = ['name','ln','la','trust_code','local_or_remote','address','contact','mobile','is_salvager_unit','area_id'];
           new Model("tyibs.base.maintenance.company").query(query).filter([]).all().then(function (records) {
               records.forEach(function (item) {
                   self.add_marker(item);
               })
           })
       },
       add_marker: function (record) {
            var self = this;
            var point = new BMap.Point(record.ln, record.la);
            var icon = new BMap.Icon("/lift_base/static/src/img/salvager_unit.png",new BMap.Size(32,32));
            var marker = new BMap.Marker(point, {icon: icon});

            marker.setTitle(record.name);
            // 维保单位ID
            marker.id = record.id;
            // 维保单位name
            marker.name = record.name;
            //是否二级救援单位
            marker.is_salvager_unit = record.is_salvager_unit;
            //区县ID
            marker.area_id = record.area_id ? record.area_id[0] : -1;
            //区县name
            marker.area_name = record.area_id ? record.area_id[1] : "未知";
            self.unit_markers.push(marker);

            var label = new BMap.Label(record.name, {offset   : new BMap.Size(-70, -20)});
            label.setStyle({
                "color": "red",
                "max-width": "none"
            });
            marker.setLabel(label);
            self.map.addOverlay(marker);
            marker.addEventListener("click", function(e){
                var info_window_widget = new InfoWindow(self,record.id,
                    self.format_undefined_data(record.name),
                    self.format_undefined_data(record.trust_code),
                    self.format_local_or_remote(record.local_or_remote),
                    self.format_undefined_data(record.address),
                    self.format_undefined_data(record.contact),
                    self.format_undefined_data(record.mobile),
                    record.is_salvager_unit
                );
                info_window_widget.appendTo(self.$el);
                var info_window = new BMap.InfoWindow(info_window_widget.$el[0]);
                marker.openInfoWindow(info_window);
            });
       },
       show_level_one: function () {
            // 二级救援按钮
            var self = this;
            self.reset_style();
            // 设置当前所选救援单位级别
            self.is_salvager_unit = false;
            self.area_ids.forEach(function (item) {
                // 更改区县列表中二级救援单位数量
                var area_count = self.area_company_count["area" + item] ? self.area_company_count["area" + item] : 0;
                $(".area" + item).html(area_count);
            });
            // 更改全市和未知区县的二级救援单位数量
            $(".tyibs-salvager-unit-total-count").html(self.area_company_count["area-2"]);
            $(".area-1").html(self.area_company_count["area-1"] ? self.area_company_count["area-1"] : 0);
            // 显示所有一级救援单位
            self.unit_markers.forEach(function (item) {
                item.show();
            })
       },
       show_level_two: function () {
            // 二级救援按钮
            var self = this;
            self.reset_style();
            // 设置当前所选救援单位级别
            self.is_salvager_unit = true;
            self.area_ids.forEach(function (item) {
                // 更改区县列表中二级救援单位数量
                var area_count = self.area_salvager_count["area" + item] ? self.area_salvager_count["area" + item] : 0;
                $(".area" + item).html(area_count);
            });
            // 更改全市和未知区县的二级救援单位数量
            $(".tyibs-salvager-unit-total-count").html(self.area_salvager_count["area-2"]);
            $(".area-1").html(self.area_salvager_count["area-1"] ? self.area_salvager_count["area-1"] : 0);
            // 隐藏一级救援单位/显示二级救援单位
            self.unit_markers.forEach(function (item) {
                if (item.is_salvager_unit){
                    item.show();
                }else {
                    item.hide();
                }
            })
       },
       search_unit_by_area_id: function (area_id) {
            $(".tyibs_salvager_unit_search_input").val("");
            // 点击区县列表，显示区县救援单位
            var self = this;
            self.current_area_id = area_id;
            self.unit_markers.forEach(function (item) {
                if(area_id == -2 && !self.is_salvager_unit){
                    // 全市一级救援单位
                    console.log("全市一级救援单位");
                    item.show();
                }else{
                    if(area_id == -2 && self.is_salvager_unit && item.is_salvager_unit){
                        // 全市二级救援单位
                        console.log("全市二级救援单位");
                        item.show();
                    }else if(item.area_id == area_id && self.is_salvager_unit && item.is_salvager_unit){
                        // 区县二级救援
                        console.log(item.area_name,"二级救援单位");
                        item.show();
                    }else if(item.area_id == area_id && !self.is_salvager_unit){
                        // 区县一级救援
                        console.log(item.area_name,"一级救援单位");
                        item.show();
                    }else {
                        item.hide();
                    }
                }
            })
       },
       search_unit_by_id: function (unit_id) {
           var self = this;
           self.unit_markers.forEach(function (item) {
               if (item.id == unit_id){
                   item.show();
               }else{
                   item.hide();
               }
           })
       },
       get_area_company_count: function (area_company_count) {
           // 获取各区县一级救援单位数量
           this.area_company_count = area_company_count;
       },
       get_area_salvager_count: function (area_salvager_count) {
           // 获取各区县二级救援单位数量
           this.area_salvager_count = area_salvager_count;
       },
       format_undefined_data: function (data) {
           // 格式化数据
           return data == undefined || data == false || data == "false" ? "未知" : data
       },
       format_local_or_remote: function (data) {
           // 格式化本地/异地
           switch (data){
               case "local":
                   return "本地";
               case "remote":
                   return "异地";
               default:
                   return "未知";
           }
       },
       reset_style: function () {
           $(".list-group-item").removeClass("selected");
           $(".salvager-unit-city").addClass("selected");
           $(".tyibs_salvager_unit_search_input").val("");
       }
   });

   var SalvagerUnitMapAreaListWidget = Widget.extend({
        //左侧区域列表
        template: "tyibs-map-salvager-unit-list-group",
        init: function (parent) {
            this._super(parent);
            this.total_count = 0;
            this.area_company_count = [];
            this.area_salvager_count = [];
        },
        start: function () {
            var self = this;
            self.get_area_company_count();
            self.get_area_salvager_unit_count();
        },
        get_area_company_count: function () {
            // 一级救援单位(所有维保单位)
            var self = this;
            self.alive(new Model("tyibs.base.maintenance.company").query(["area_id"]).group_by(["area_id"])).then(function (results) {
                results.forEach(function (item) {
                    var area_name = item.attributes.value ? item.attributes.value[1] : "未知";
                    var area_id = item.attributes.value ? item.attributes.value[0] : -1;
                    var area_item_widget = new SalvagerUnitMapAreaItemWidget(self, area_name, item.attributes.length, area_id);
                    area_item_widget.on("search_unit_by_area_id", self, self.search_unit_by_area_id);
                    area_item_widget.appendTo(self.$el.find("ul.tyibs-map-area-list-group"));
                    self.total_count += item.attributes.length;
                    self.area_company_count["area" + area_id] = item.attributes.length;
                });
                self.$el.find(".tyibs-salvager-unit-total-count").html(self.total_count);
                self.area_company_count["area" + -2] = self.total_count;
                self.trigger("get_area_company_count", self.area_company_count);
            })
        },
        get_area_salvager_unit_count: function () {
            // 二级救援单位
            var self = this;
            self.alive(new Model("tyibs.base.maintenance.company").query(["area_id"]).filter([['is_salvager_unit', '=', true]]).group_by(["area_id"])).then(function (results) {
                var salvager_total_count = 0;
                results.forEach(function (item) {
                    var area_id = item.attributes.value ? item.attributes.value[0] : -1;
                    salvager_total_count += item.attributes.length;
                    self.area_salvager_count["area" + area_id] = item.attributes.length;
                });
                self.area_salvager_count["area" + -2] = salvager_total_count;
                self.trigger("get_area_salvager_count", self.area_salvager_count);
            })
        },
        search_unit_by_area_id: function (area_id) {
            var self = this;
            self.trigger("search_unit_by_area_id", area_id);
        },
        events: {
            "click li.salvager-unit-city": function () {
                this.search_unit_by_area_id(-2);
            },
            "click li": function (e) {
                $(".list-group-item").removeClass("selected");
                $(e.currentTarget).addClass("selected");
                $(this).addClass("selected");
            }
        }
    });

   var SalvagerUnitMapAreaItemWidget = Widget.extend({
        //左侧区域列表的item
        template: "tyibs-map-salvager-unit-item",
        init: function (parent, name, count, id) {
            this._super(parent);
            this.name = name;
            this.count = count;
            this.id = id;
        },
        events: {
            "click": function (e) {
                this.trigger("search_unit_by_area_id", this.id);
            }
        }

    });

   var InfoWindow = Widget.extend({
       template: "baidu_map_salvager_unit_info_window",
       init: function (parent, id, name, trust_code, local_or_remote, address, contact, mobile, is_salvager_unit) {
           this.id = id;
           this.name = name;
           this.trust_code = trust_code;
           this.local_or_remote = local_or_remote;
           this.address = address;
           this.contact = contact;
           this.mobile = mobile;
           this.level = is_salvager_unit ? "二级救援" : "一级救援";
           this._super(parent);
       },
       events: {
           "click h4": function (e) {
               this.do_action({
                    name: this.name,
                    type: 'ir.actions.act_window',
                    res_model: "tyibs.base.maintenance.company",
                    res_id: this.id,
                    views: [[false, 'form']],
                    target: 'current',
                    context: {},
               })
           }
       }
   });

   // 按钮区
    var SalvagerUnitMapBtnBlock = Widget.extend({
        template: "tyibs-map-salvager-unit-btn-block",
        init: function (parent) {
            this._super(parent);
        },
        events: {
            "click button.tyibs-map-salvager-unit-btn": function (e) {
                this.trigger(e.target.value);
            }
        }
    });

    // 搜索框
    var SalvagerUnitSearchWidget = Widget.extend({
        template: "tyibs-map-salvager-unit-search",
        init: function (parent, units_markers) {
            this._super(parent);
            this.units_markers = units_markers;
        },
        start: function () {
           this.autocomplete();
        },
        autocomplete: function () {
            var self = this;
            self.$el.find(".tyibs_salvager_unit_search_input").autocomplete({
                source: function (request, response) {
                    var response_vals = [];
                    for(var i=0; i < self.units_markers.length; i++){
                        if (self.units_markers[i].name.indexOf($.trim(request.term)) > -1){
                            response_vals.push({id:self.units_markers[i].id,label:self.units_markers[i].name,value:self.units_markers[i].name});
                        }
                        if (response_vals.length == 10){
                            break;
                        }
                    }
                    response(response_vals);
                },
                select: function( event, ui ) {
                    self.trigger("search_unit_by_id", ui.item.id);
                }
            });
        }
    });
    
    core.action_registry.add("lift_base.salvager_unit_map", SalvagerUnitMap);

});